/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： FunctionAuthorityInterceptor.java
 * Date：18-11-5 上午11:10
 * Author: guomw
 */

package com.guomw.report.web.config;

import com.alibaba.fastjson.JSON;
import com.guomw.report.common.enums.AppCode;
import com.guomw.report.common.utils.ApiResult;
import com.guomw.report.service.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能权限拦截器
 *
 * @author guomw
 * @date 2018/9/25
 */
public class FunctionAuthorityInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("utf-8");
        Integer operatorId = null;
        if (httpServletRequest.getSession().getAttribute("OwnerId") != null) {
            operatorId = Integer.valueOf(httpServletRequest.getSession().getAttribute("OwnerId").toString());
        }
        boolean checked = false;
        if (operatorId != null && operatorId > 0) {
            checked = systemService.checkOperatorPathPower(operatorId, httpServletRequest, true);
            if (!checked) {
                httpServletResponse.getWriter().write(JSON.toJSONString(ApiResult.resultWith(AppCode.NOT_AUTHORITY)));
                return false;
            }
        }
        if (!checked) {
            httpServletResponse.getWriter().write(JSON.toJSONString(ApiResult.resultWith(AppCode.NOT_AUTHORITY)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
